package com.piggy.logi.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.piggy.common.core.exception.base.BaseException;
import com.piggy.common.core.utils.PageUtils;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.logi.sys.api.domain.LogiSysDictData;
import com.piggy.logi.sys.api.domain.LogiSysDictType;
import com.piggy.logi.sys.mapper.LogiSysDictDataMapper;
import com.piggy.logi.sys.service.ILogiSysDictDataService;
import com.piggy.logi.sys.service.ILogiSysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author shark
 */
@Service
public class LogiSysDictDataServiceImpl extends ServiceImpl<LogiSysDictDataMapper, LogiSysDictData> implements ILogiSysDictDataService {

    @Autowired
    private ILogiSysDictTypeService dictTypeService;

    @Override
    public TableDataInfo<LogiSysDictData> selectPageDictDataList(LogiSysDictData dictData) {
        LambdaQueryWrapper<LogiSysDictData> lqw = new LambdaQueryWrapper<LogiSysDictData>()
                .eq(StrUtil.isNotBlank(dictData.getDictType()), LogiSysDictData::getDictType, dictData.getDictType())
                .like(StrUtil.isNotBlank(dictData.getDictLabel()), LogiSysDictData::getDictLabel, dictData.getDictLabel())
                .eq(StrUtil.isNotBlank(dictData.getStatus()), LogiSysDictData::getStatus, dictData.getStatus())
                .eq(StrUtil.isNotBlank(dictData.getListClass()), LogiSysDictData::getListClass, dictData.getListClass())
                .in(CollectionUtil.isNotEmpty(dictData.getDictKeyList()), LogiSysDictData::getDictValue, dictData.getDictKeyList())
				.in(LogiSysDictData::getDeptId, Lists.newArrayList(0, ObjectUtil.defaultIfNull(dictData.getDeptId(),0L)))
				.notInSql(ObjectUtil.isNotEmpty(dictData.getDeptId()) && dictData.getDeptId() > 0L, LogiSysDictData::getDictType,
						String.format(" select dict_type from logi_sys_dict_type where dept_id=0 and dict_type in (select distinct dict_type from logi_sys_dict_type where dept_id=%d) ", dictData.getDeptId()))
				.orderByAsc(LogiSysDictData::getDictSort);
        return PageUtils.buildDataInfo(page(PageUtils.buildPage(), lqw));
    }

    /**
     * 获取字典标签列表(dictType必输，remark、dictKeyList选输)
     */
    @Override
    public List<LogiSysDictData> getDictList(LogiSysDictData dictData) {
        String dictType = dictData.getDictType();
        if (StrUtil.isEmpty(dictType)) {
            throw new BaseException("字典类型不能为空");
        }
        List<LogiSysDictData> dictDataList = null;

        String remark = dictData.getRemark();
        List<String> dictKeyList = dictData.getDictKeyList();
        LambdaQueryWrapper<LogiSysDictData> lqw;
        if (StrUtil.isNotEmpty(remark) && CollectionUtil.isNotEmpty(dictKeyList)) {
            //listClass不为空，dictKeyList不为空
            //dictDataList=this.list(new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus,0).eq(LogiSysDictData::getDictType,dictType).eq(LogiSysDictData::getRemark,remark).in(LogiSysDictData::getDictValue,dictKeyList).orderByAsc(LogiSysDictData::getDictSort));
            lqw = (new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus, 0).eq(LogiSysDictData::getDictType, dictType).eq(LogiSysDictData::getRemark, remark).in(LogiSysDictData::getDictValue, dictKeyList).orderByAsc(LogiSysDictData::getDictSort));
        } else if (StrUtil.isNotEmpty(remark) && CollectionUtil.isEmpty(dictKeyList)) {
            //listClass不为空，dictKeyList为空
            //dictDataList=this.list(new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus,0).eq(LogiSysDictData::getDictType,dictType).eq(LogiSysDictData::getRemark,remark).orderByAsc(LogiSysDictData::getDictSort));
            lqw = (new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus, 0).eq(LogiSysDictData::getDictType, dictType).eq(LogiSysDictData::getRemark, remark).orderByAsc(LogiSysDictData::getDictSort));
        } else if (StrUtil.isEmpty(remark) && CollectionUtil.isNotEmpty(dictKeyList)) {
            //listClass为空，dictKeyList不为空
            //dictDataList=this.list(new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus,0).eq(LogiSysDictData::getDictType,dictType).in(LogiSysDictData::getDictValue,dictKeyList).orderByAsc(LogiSysDictData::getDictSort));
            lqw = (new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus, 0).eq(LogiSysDictData::getDictType, dictType).in(LogiSysDictData::getDictValue, dictKeyList).orderByAsc(LogiSysDictData::getDictSort));
        } else {
            //dictDataList=this.list(new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus,0).eq(LogiSysDictData::getDictType,dictType).orderByAsc(LogiSysDictData::getDictSort));
            lqw = (new LambdaQueryWrapper<LogiSysDictData>().eq(LogiSysDictData::getStatus, 0).eq(LogiSysDictData::getDictType, dictType).orderByAsc(LogiSysDictData::getDictSort));
        }
		lqw.in(LogiSysDictData::getDeptId, Lists.newArrayList(0, ObjectUtil.defaultIfNull(dictData.getDeptId(),0L)));
        lqw.notInSql(ObjectUtil.isNotEmpty(dictData.getDeptId()) && dictData.getDeptId() > 0L, LogiSysDictData::getDictType,
                String.format(" select dict_type from logi_sys_dict_type where dept_id=0 and dict_type in (select distinct dict_type from logi_sys_dict_type where dept_id=%d) ", dictData.getDeptId()));

        return this.list(lqw);
    }

    /**
     * 根据条件分页查询字典数据
     *
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<LogiSysDictData> selectDictDataList(LogiSysDictData dictData) {
        return list(new LambdaQueryWrapper<LogiSysDictData>()
                .eq(StrUtil.isNotBlank(dictData.getDictType()), LogiSysDictData::getDictType, dictData.getDictType())
                .like(StrUtil.isNotBlank(dictData.getDictLabel()), LogiSysDictData::getDictLabel, dictData.getDictLabel())
                .eq(StrUtil.isNotBlank(dictData.getStatus()), LogiSysDictData::getStatus, dictData.getStatus())
				.in(LogiSysDictData::getDeptId, Lists.newArrayList(0, ObjectUtil.defaultIfNull(dictData.getDeptId(),0L)))
                .notInSql(ObjectUtil.isNotEmpty(dictData.getDeptId()) && dictData.getDeptId() > 0L, LogiSysDictData::getDictType,
                        String.format(" select dict_type from logi_sys_dict_type where dept_id=0 and dict_type in (select distinct dict_type from logi_sys_dict_type where dept_id=%d) ", dictData.getDeptId()))
                .orderByAsc(LogiSysDictData::getDictSort));
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(Long deptId, String dictType, String dictValue) {
        LogiSysDictData sysDictData = getOne(new LambdaQueryWrapper<LogiSysDictData>()
                .select(LogiSysDictData::getDictLabel)
                .in(LogiSysDictData::getDeptId, Lists.newArrayList(0, ObjectUtil.defaultIfNull(deptId,0L)))
                .notInSql(ObjectUtil.isNotEmpty(deptId) && deptId > 0L, LogiSysDictData::getDictType,
                        String.format(" select dict_type from logi_sys_dict_type where dept_id=0 and dict_type in (select distinct dict_type from logi_sys_dict_type where dept_id=%d) ", deptId))
				.eq(LogiSysDictData::getDictType, dictType)
                .eq(LogiSysDictData::getDictValue, dictValue));
        if (sysDictData != null) {
            return sysDictData.getDictLabel();
        } else {
            return "";
        }
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public LogiSysDictData selectDictDataById(Long dictCode) {
        return getById(dictCode);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteDictDataByIds(Long[] dictCodes) {
        baseMapper.deleteBatchIds(Arrays.asList(dictCodes));
    }

    /**
     * 新增保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int insertDictData(LogiSysDictData data) {
        LogiSysDictType type = dictTypeService.selectDictTypeByType(data.getDeptId(), data.getDictType());
        if (type.getDeptId() == 0L) {
            dictTypeService.insertDictType(type.setCreateTime(new Date()).setDictId(null).setDeptId(data.getDeptId()));
        }
        return baseMapper.insert(data);
    }

    /**
     * 修改保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    public int updateDictData(LogiSysDictData data) {
        LogiSysDictType type = dictTypeService.selectDictTypeByType(data.getDeptId(), data.getDictType());
        if (type.getDeptId() == 0L) {
            dictTypeService.insertDictType(type.setCreateTime(new Date()).setDictId(null).setDeptId(data.getDeptId()));
        }
        LogiSysDictData old = getById(data.getDictCode());
        if (old.getDeptId() == 0L) {
            return insertDictData(data.setDictCode(null));
        }
        return baseMapper.updateById(data);
    }
}
